﻿
/*
 * @time：2014年11月16日 13:17:37
 * @author：ethan
 * @email：ling121211@gmail.com
 */ 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using Microsoft.Office.Interop.PowerPoint;

using Aspose.Words;
using org.pdfbox.pdmodel;
using org.pdfbox.util;

using NPOI.HSSF.UserModel;
using NPOI.HSSF.Extractor;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI.OpenXml4Net.OPC;
using NPOI;
using NPOI.XWPF.Extractor;

namespace XMK.Utils
{
    /// <summary>
    /// 文件帮助类
    /// </summary>
    public class FileHelper
    {
        public static string ReadText(string filePath)
        {
            string fileText = string.Empty;
            string fileType = Path.GetExtension(filePath).ToLower();
            try
            {
                switch (fileType)
                {
                    case ".doc":
                    case ".docx":
                        Document doc = new Document(filePath);
                        fileText = doc.GetText();
                        break;
                    case ".pdf":
                        PDDocument pdf = PDDocument.load(filePath);
                        PDFTextStripper pdfStripper = new PDFTextStripper();
                        fileText = pdfStripper.getText(pdf);
                        pdf.close();
                        break;
                    case ".txt":
                        fileText = File.ReadAllText(filePath, Encoding.GetEncoding("gb2312"));
                        break;
                    case ".xls":
                    case ".xlsx":
                        using (FileStream fs = new FileStream(filePath, FileMode.Open))
                        {
                            StringBuilder sb = new StringBuilder();
                            // 构造 XSSFWorkbook 对象，strPath 传入文件路径  
                            IWorkbook workBook = null;
                            int sheetCount = 0;
                            // 读取第一章表格内容  

                            if (Path.GetExtension(filePath).ToLower().Equals(".xlsx"))
                            {
                                workBook = new XSSFWorkbook(fs);
                                sheetCount = workBook.NumberOfSheets;
                                for (int i = 0; i < sheetCount; i++)
                                {

                                    XSSFSheet sheet = workBook.GetSheetAt(i) as XSSFSheet;
                                    _ExtractSheetText(sb, sheet);
                                }
                                fileText = sb.ToString();
                            }
                            else
                            {
                                POIFSFileSystem poiFSSys = new POIFSFileSystem(fs);
                                ExcelExtractor extractor = new ExcelExtractor(poiFSSys);
                                fileText = extractor.Text;

                                //workBook = new HSSFWorkbook(fs);
                                //sheetCount = workBook.NumberOfSheets;
                                //for (int i = 0; i < sheetCount; i++)
                                //{
                                //    HSSFSheet sheet = workBook.GetSheetAt(i) as HSSFSheet;
                                //    _ExtractSheetText(sb, sheet);
                                //}
                            }

                        }
                        
                            
                        break;
                    case ".ppt":
                    case ".pptx":
                        fileText = _ExtractTextFromPPT(filePath);
                        break;
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(LogType.Error, string.Format("路径：{0} 报错！{1}", filePath, ex.ToString()));                
            }
            
            return fileText.Trim().Replace("\a", "");
        }

        private static void _ExtractSheetText(StringBuilder sb, ISheet sheet)
        {
            // 定义 row、cell  
            IRow row;
            // 循环输出表格中的内容  
            for (int i = sheet.FirstRowNum; i < sheet.PhysicalNumberOfRows; i++)
            {
                row = sheet.GetRow(i);
                if (row == null) continue;
                for (int j = row.FirstCellNum; j < row.PhysicalNumberOfCells; j++)
                {
                    sb.AppendFormat("{0}  ", row.Cells[j]);
                }
            }
        }

        protected static string _ExtractTextFromPPT(string file)
        {
            StringBuilder sb = new StringBuilder();
            // 1. 添加 COM 组件：Microsoft PowerPoint 14.0 Object Library
            // 2. 将该引用的属性：嵌入互操作类型-false
            try
            {
                Application pa = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
                Microsoft.Office.Interop.PowerPoint.Presentation pp =
                    pa.Presentations.Open(file,
                    Microsoft.Office.Core.MsoTriState.msoTrue,
                    Microsoft.Office.Core.MsoTriState.msoFalse,
                    Microsoft.Office.Core.MsoTriState.msoFalse);
                //开始读取每一页
                foreach (Microsoft.Office.Interop.PowerPoint.Slide slide in pp.Slides)
                {
                    //开始读取每一个数据块
                    foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
                    {
                        if (shape.TextFrame.HasText == Microsoft.Office.Core.MsoTriState.msoFalse) continue;
                        sb.Append(shape.TextFrame.TextRange.Text);
                    }
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(LogType.Error,
                    string.Format("读取PPT内容异常 || {0}", ex.ToString()));
            }
            
            return sb.ToString().Trim();
        }
    }
}
